package com.dshore.messagecenter.service.topicQueue.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.dshore.messagecenter.dao.topicqueue.TopicAccessDao;
import com.dshore.messagecenter.dao.topicqueue.TopicQueueDao;
import com.dshore.messagecenter.dao.topicqueue.TopicSendDao;
import com.dshore.messagecenter.model.system.SysDict;
import com.dshore.messagecenter.model.topicqueue.MdTopic;
import com.dshore.messagecenter.model.topicqueue.MdTopicAccess;
import com.dshore.messagecenter.model.topicqueue.MdTopicSend;
import com.dshore.messagecenter.service.topicQueue.ServiceAccessService;
import com.dshore.messagecenter.util.RabbitUtil;


@Service
public class ServiceAccessServiceImpl implements ServiceAccessService {
	@Value("${spring.rabbitmq.virtual-host}")
	private String vhostName;
	@Value("${access_url}")
	private String accessUrl;
	@Autowired
	private TopicQueueDao topicQueueDao;
	@Autowired
	private TopicAccessDao topicAccessDao;
	@Autowired
	private TopicSendDao topicSendDao;
/*	@Autowired
	private RabbitPublish rabbitPublish;*/
	@Autowired
	private RabbitUtil rabbitUtil;
	/**
	 * 修改时获取服务接入数据
	 */
	@Override
	public Map<String, Object> getSerivceInfo(String topicQueueNo, String id) {
		//初始化Session中Map
		Map<String, Object> map = new HashMap<>();
		MdTopic mdTopic=topicSendDao.selectByTopic(id);
		MdTopicAccess mdTopicAccess=topicSendDao.selectByTopicAccess(topicQueueNo);
		List<MdTopicSend>mdTopicSends=topicSendDao.selectByServiceAccess(topicQueueNo);
		map.put("ServiceName", mdTopic.getTopicQueueName());
		map.put("id", mdTopic.getId());
		map.put("topicQueueNo", topicQueueNo);
		map.put("status", mdTopic.getStatus());
		Map<String, String> template = new HashMap<>();
		if(mdTopic.getTemplateId()!=null) {
			template.put("templateId", mdTopic.getTemplateId());
			template.put("templateName",mdTopic.getTemplateName());
		}
		Map<String, String> origin = new HashMap<>();
		origin.put("originId", mdTopicAccess.getAccessAppid());
		origin.put("originName", mdTopicAccess.getAccessAppName());
		origin.put("id", mdTopicAccess.getId());
		map.put("origin", origin);
		List<Map<String,Object>> targetList = new ArrayList<>();
		map.put("template", template);
		if(mdTopicSends.size()>0) {
			for(int i=0;i<mdTopicSends.size();i++) {
				Map<String, Object> send = new HashMap<>();
				send.put("sendType", mdTopicSends.get(i).getSendType());
				send.put("sendChannel", mdTopicSends.get(i).getTargetUrl());
				send.put("sendName", mdTopicSends.get(i).getSendName());
				send.put("targetId", mdTopicSends.get(i).getTargetAppId());
				send.put("targetName",mdTopicSends.get(i).getTargetAppName());
				send.put("status","0");
				targetList.add(send);
			}
		}
		map.put("targetList", targetList);
/*		map.put("his_targetList", targetList);*/
		map.put("edit", 1);
		return map;
	}
	
	//更新服务接入数据
	@SuppressWarnings("unchecked")
	@Override
	public void updateService(Map<String, Object> map) {
		try{
			List<Map<String,String>> targetList=(List<Map<String,String>>)map.get("targetList");
			String id=(String)map.get("id");
			String status=topicSendDao.selectByStatus(id);
			String NameStatus=checkAppName((String)map.get("ServiceName"), id);
		if(NameStatus.equals("true")) {
			if(status.equals("1301")) {
				//未发布走这里
				Map<String,String>template=(Map<String,String>)map.get("template");
				//主题队列信息
				MdTopic mdTopic=new MdTopic();
				String ServiceName=(String)map.get("ServiceName");
				/*String AppNum=String.valueOf(targetList.size());*/
				mdTopic.setTopicQueueName(ServiceName.trim());
				/*mdTopic.setTargetAppNum(AppNum);*/
				mdTopic.setId(id);
				if(template!=null) {
					mdTopic.setTemplateId((String)template.get("templateId"));
				}
				topicSendDao.UpdateByTopic(mdTopic);
				//主题接入信息表
				MdTopicAccess mdTopicAccess = new MdTopicAccess();
				//源应用
				Map<String,String>origin=(Map<String,String>)map.get("origin");
				mdTopicAccess.setAccessAppid(origin.get("originId"));
				mdTopicAccess.setId(origin.get("id"));
				topicSendDao.UpdateByTopicAccess(mdTopicAccess);
				//主题发送信息
				String topicQueueNo=(String)map.get("topicQueueNo");
				topicSendDao.UpdateByServiceAccess(topicQueueNo);
				//新增发送信息
				List<MdTopicSend>MdTopicSends=new ArrayList<MdTopicSend>();
				for(int i=0;i<targetList.size();i++) {
					MdTopicSend mdTopicSend =new MdTopicSend();
					Map<String, String>send=targetList.get(i);
					mdTopicSend.setSendType(send.get("sendType"));
					mdTopicSend.setTargetAppId(send.get("targetId"));
					mdTopicSend.setTargetUrl(send.get("sendChannel"));
					mdTopicSend.setTopicQueueNo(topicQueueNo);
					mdTopicSend.setSeq(i);
					MdTopicSends.add(mdTopicSend);
				}
				topicSendDao.saveService(MdTopicSends);
			}else {
				MdTopic mdTopic=new MdTopic();
				String ServiceName=(String)map.get("ServiceName");
				Map<String,String>template=(Map<String,String>)map.get("template");
				mdTopic.setTopicQueueName(ServiceName.trim());
				if(template!=null) {
					mdTopic.setTemplateId((String)template.get("templateId"));
				}
				mdTopic.setId(id);
				topicSendDao.UpdateByTopic(mdTopic);
				//发布走这里
				rabbitUtil.updateTargetApp((String)map.get("topicQueueNo"), targetList);
			}
			}else {
				
			}
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
	//查看服务接入配置
	@Override
	public Map<String, Object> queryById(String id) {
		//主题队列信息
		MdTopic mdTopic=topicSendDao.selectByTopicConfig(id);
		//源应用
		MdTopicAccess mdTopicAccess=topicSendDao.selectByTopicAccessConfig(mdTopic.getTopicQueueNo());
		//目标应用
		List<MdTopicSend>MdTopicSends=topicSendDao.selectByServiceAccessConfig(mdTopic.getTopicQueueNo());
		Map<String, Object> serviceAccess = new HashMap<String, Object>();
		serviceAccess.put("mdTopic",mdTopic);
		serviceAccess.put("mdTopicAccess",mdTopicAccess);
		serviceAccess.put("MdTopicSends",MdTopicSends);
		return serviceAccess;
	}
	//新增服务接入
		@SuppressWarnings("unchecked")
		@Override
		public Object saveService(Map<String, Object> map) {
			try {
				     String NameStatus=checkAppName((String)map.get("ServiceName"), "");
				     if(NameStatus.equals("true")) {
						String topicQueueNo=selectTopic();
						int num=topicSendDao.selectByCode(topicQueueNo);
						int nums=topicSendDao.selectByAccessCode(topicQueueNo);
						if(num!=0||nums!=0) {
							return false;
						}else {
							//源应用
							Map<String,String>origin=(Map<String,String>)map.get("origin");
							//模板
							Map<String,String>template=(Map<String,String>)map.get("template");
							//队列名称
							String ServiceName=(String)map.get("ServiceName");
							//发送方式和目标应用
							List<Map<String,String>>targetList=(List<Map<String,String>>)map.get("targetList");
							//主题信息表
							MdTopic mdTopic=new MdTopic();
							mdTopic.setTopicQueueNo(topicQueueNo);
							mdTopic.setVhostName(vhostName);
							mdTopic.setTopicQueueName(ServiceName.trim());
							if(template!=null) {
								if(StringUtils.isNotBlank(template.get("templateId"))) {
								mdTopic.setTemplateId(template.get("templateId"));
								}
							}
							topicQueueDao.saveService(mdTopic);
							//主题接入信息表
							MdTopicAccess mdTopicAccess = new MdTopicAccess();
							mdTopicAccess.setAccessAppid(origin.get("originId"));
							mdTopicAccess.setTopicQueueNo(topicQueueNo);
							mdTopicAccess.setAccessUrl(accessUrl);
							topicAccessDao.saveService(mdTopicAccess);
							//主题发送信息
							List<MdTopicSend>MdTopicSends=new ArrayList<MdTopicSend>();
							for(int i=0;i<targetList.size();i++) {
								MdTopicSend mdTopicSend =new MdTopicSend();
								Map<String,String>send=targetList.get(i);
								mdTopicSend.setSendType(send.get("sendType"));
								mdTopicSend.setTargetAppId(send.get("targetId"));
								if(StringUtils.isNotBlank(send.get("sendChannel"))) {
									if(StringUtils.isNotBlank(send.get("sendChannel").trim())) {
										mdTopicSend.setTargetUrl(send.get("sendChannel").trim());
									}
								}
								
								mdTopicSend.setTopicQueueNo(topicQueueNo);
								mdTopicSend.setSeq(i);
								MdTopicSends.add(mdTopicSend);
								if(StringUtils.isNotBlank(send.get("sendConfig"))) {
									mdTopicSend.setSendConfig(send.get("sendConfig"));
								}
								
							}
							topicSendDao.saveService(MdTopicSends);
					return mdTopic.getId();
				}
			}else {
				return false;
			}
		}catch(Exception e) {
			e.printStackTrace();
			return false;
		}
	 }
//新增校验姓名是否重复
		@Override
		public String checkAppName(String name, String id) {
			if(StringUtils.isNotBlank(name.trim())) {
				List<MdTopic> mdtopics=topicSendDao.selectBycheckName(name.trim());
				if(mdtopics.size()>1) {
					return "false";
				}else if (mdtopics.size()==0) {
					return "true";
				}else {
					if(StringUtils.isNotBlank(id)) {
						if(mdtopics.get(0).getId().equals(id)) {
							return "true";
						}else {
							return "false";
						}
					}else {
						return "false";
					}
				}
			}else {
				return "false";
			}
		}
//查看是否发布
		@Override
		public String selectByStatus(String id) {
			String status=topicSendDao.selectByStatus(id);
			if(status.equals("1302")) {
				return "false";
			}else {
				return "true";
			}
		}
		/**
		 * 查询发布方式
		 */
		@Override
		public List<SysDict> selectBySendType() {
			return topicSendDao.selectBySendType();
		}
		//新增时查询topic编码
		public  String selectTopic() {
			//查询递增的最后一条主题队列编码
			List<String> topicQueueNos = topicQueueDao.queryAllQueueSigns();
		    //确定主题队列编码topicQueueNo
		    String topicQueueNo = new StringBuffer("TOPIC").append(String.format("%06d", 1)).toString();//一条数据没有则默认 TOPIC000001 
			//截取TOPIC前5位数，取后面数字递增
		    if(topicQueueNos.size() > 0) {
		        topicQueueNo = topicQueueNos.get(0).substring(5); 
		    	if( StringUtils.isNotBlank(topicQueueNo)) {
		    		//递增
		            int queueNum = Integer.parseInt(topicQueueNo) + 1;
		            //递增后自动补6位
		            topicQueueNo = new StringBuffer("TOPIC").append(String.format("%06d", queueNum)).toString();
		    	}
		     }
			return topicQueueNo;
		}

}
